//
//  YYGestureLockView.m
//  mushaofengDemo
//
//  Created by user on 15/7/17.
//  Copyright (c) 2015年 user. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import "YYGestureLockView.h"
@interface YYGestureLockView()<UIAlertViewDelegate>
{
    KKGestureLockView * lockView;
    int  wrongTimes;//记录错误的次数
    NSString * lastString;//记录上次的密码
    BOOL     isRight;
}
@property (nonatomic,unsafe_unretained)GestureLockType  gestureLockType;
@end

@implementation YYGestureLockView


-(id)initWithFrame:(CGRect)frame andGestureType:(GestureLockType)gestureType
{
    if (self = [super initWithFrame:frame])
    {
        self.backgroundColor = RGBA(26, 34, 45, 1);
        _gestureLockType = gestureType;
        //为图形锁设置背景图片
        UIImageView * backImageView = [[UIImageView alloc]initWithFrame:self.frame];
        backImageView.userInteractionEnabled = TRUE;
        [self addSubview:backImageView];
        //设置lockview的各种基本设置
        lockView = [[KKGestureLockView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
        lockView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
        lockView.normalGestureNodeImage = [UIImage imageNamed:@"shoushi1.png"];
        lockView.selectedGestureNodeImage = [UIImage imageNamed:@"shoushi2.png"];
        lockView.lineColor = [[UIColor whiteColor] colorWithAlphaComponent:1];
        lockView.lineWidth = 2;
        lockView.delegate = self;
        if (SCREEN_HEIGHT == 480)
        {
            lockView.contentInsets = UIEdgeInsetsMake(120, (SCREEN_WIDTH - 250)/2, 80, (SCREEN_WIDTH - 250)/2);
        }else
        {
            if (_gestureLockType == verifyGestureLock)
            {
                lockView.titleLabel.center = CGPointMake(self.center.x, 70);
                lockView.userLabel.center = CGPointMake(self.center.x, 100);
                lockView.tipLabel.center = CGPointMake(self.center.x, 130);
               lockView.contentInsets = UIEdgeInsetsMake((SCREEN_HEIGHT - 250)/2, (SCREEN_WIDTH - 250)/2, (SCREEN_HEIGHT - 250)/2, (SCREEN_WIDTH - 250)/2);
            }else
            {
           lockView.contentInsets = UIEdgeInsetsMake((SCREEN_HEIGHT - 350)/2, (SCREEN_WIDTH - 250)/2, (SCREEN_HEIGHT - 350)/2, (SCREEN_WIDTH - 250)/2);
            }
        }
        
        [self addSubview:lockView];
        
        wrongTimes = 0; //错误次数
        //设置密码
        if(gestureType == setGestureLock)
        {
            lockView.tipLabel.text = @"请滑动绘制密码";
            [lockView.forgotPsdBtn setTitle:@"取消" forState:UIControlStateNormal];
        }
        //验证密码
        if (gestureType == verifyGestureLock)
        {
            lockView.tipLabel.text = @"请滑动输入密码";
            [lockView.forgotPsdBtn setTitle:@"忘记密码？" forState:UIControlStateNormal];
        }
        //重置密码
        if (gestureType == reSetGestureLock)
        {
            lockView.tipLabel.text = @"请输入旧密码";
            [lockView.forgotPsdBtn setTitle:@"取消" forState:UIControlStateNormal];
        }
        
        lastString = nil;

    }
    return self;
}
- (void)gestureLockView:(KKGestureLockView *)gestureLockView didBeginWithPasscode:(NSString *)passcode{
    
}

- (void)gestureLockView:(KKGestureLockView *)gestureLockView didEndWithPasscode:(NSString *)passcode{
    if(passcode.length<7)
    {
        //绘制小于四个点，直接返回
        ALERT_VIEW(@"请至少绘制四个点");
        return;
    }
    //设置密码
    if(self.gestureLockType == setGestureLock)
    {
        
        if (lastString)//存在，代表第二次输入
        {
            if ([lastString isEqualToString: passcode])
            {
                ALERT_VIEW(@"手势密码设置成功");
                //成功后，将lastString置空，并且将密码保存在本地
                lastString = nil;
                [[NSUserDefaults standardUserDefaults] setObject:passcode forKey:@"GesturePsd"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                if ([_yyGestureDelegate respondsToSelector:@selector(gestureSuccess)])
                {
                 [_yyGestureDelegate gestureSuccess];//启动成功后的代理
                }
            }else
            {
               
                ALERT_VIEW(@"两次不一致");
                lastString = nil;
                
                lockView.tipLabel.text = @"请重新滑动绘制密码";
                [self shapeTheLockViewTiplabel];
                
                return;
            }
        }else
        {
            lockView.tipLabel.text = @"请再次滑动绘制密码";
            lastString = passcode;
        }
        
    }
    //验证密码
    if (self.gestureLockType == verifyGestureLock)
    {
        
        if ([passcode isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"GesturePsd"]])
        {
            if ([_yyGestureDelegate respondsToSelector:@selector(gestureSuccess)])
            {
                [_yyGestureDelegate gestureSuccess];//启动成功后的代理
            }
        }else
        {
            wrongTimes ++ ;
           
            if (wrongTimes == 5)
            {
                if ([_yyGestureDelegate respondsToSelector:@selector(gestureFailed)])
                {
                    [_yyGestureDelegate gestureFailed];//启动成功后的代理
                }
                
            }
            
            NSString * textString = [NSString stringWithFormat:@"密码不正确,还剩下%d次机会",5-wrongTimes];
            lockView.tipLabel.text = textString;
            [self shapeTheLockViewTiplabel];
         
        }
    }
    //修改密码
    if (self.gestureLockType == reSetGestureLock)
    {
        
        if (isRight == FALSE)
        {
            //输入密码成功后，让isRight为yes
            if ([passcode isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"GesturePsd"]])
            {
                //旧密码输入成功
                lockView.tipLabel.text = @"请滑动绘制新密码";
                isRight = TRUE;
            }else
            {
                wrongTimes ++ ;
                
                if (wrongTimes == 5)
                {
                    if ([_yyGestureDelegate respondsToSelector:@selector(gestureFailed)])
                    {
                        [_yyGestureDelegate gestureFailed];//启动成功后的代理
                    }
                    
                }
                NSString * textString = [NSString stringWithFormat:@"密码不正确,还剩下%d次机会",5-wrongTimes];
                lockView.tipLabel.text = textString;
                [self shapeTheLockViewTiplabel];
                
            }
            return;
            
        }
        
        if (lastString)//存在，代表第二次输入
        {
            if ([lastString isEqualToString: passcode])
            {
                ALERT_VIEW(@"修改成功");
                //成功后，将lastString置空，并且将密码保存在本地
                lastString = nil;
                [[NSUserDefaults standardUserDefaults] setObject:passcode forKey:@"GesturePsd"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                if ([_yyGestureDelegate respondsToSelector:@selector(gestureSuccess)])
                {
                    [_yyGestureDelegate gestureSuccess];//启动成功后的代理
                }
                
            }else
            {
                ALERT_VIEW(@"两次密码不一致");
                lastString = nil;
                lockView.tipLabel.text = @"请重新滑动绘制密码";
                [self shapeTheLockViewTiplabel];
                return;
            }
        }else
        {
            lockView.tipLabel.text = @"请再次滑动绘制密码";
            lastString = passcode;
        }
        
    }
}
//让label摇晃的动画
-(void)shapeTheLockViewTiplabel
{
    CAKeyframeAnimation * shakeAnima = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
    // 2. 设置动画属性
    [shakeAnima setValues:@[@(12.0f*M_PI/180.0f), @(-12.0f*M_PI/180.0f), @(12.0f*M_PI/180.0f),@(0.0f*M_PI/180.0f)]];
    shakeAnima.repeatCount=1;
    [lockView.tipLabel.layer addAnimation:shakeAnima forKey:@"1"];

    NSURL *url=[[NSBundle mainBundle]URLForResource:@"glass.wav" withExtension:nil];
    SystemSoundID soundID=0;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
    AudioServicesPlayAlertSound(soundID);
}
@end
